package com.i5.distributedlock.service.impl.zookeeper;

import com.i5.distributedlock.core.key.LockKey;
import com.i5.distributedlock.core.key.ZookeeperLockKey;
import com.i5.distributedlock.exception.LockFailException;
import com.i5.distributedlock.service.LockService;
import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.recipes.locks.InterProcessMutex;
import org.apache.curator.framework.recipes.locks.InterProcessReadWriteLock;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;

public class ReadZkLockServiceImpl implements LockService {

	@Qualifier("lockCuratorClient")
	@Autowired
	private CuratorFramework lockCuratorClient;

	private ZookeeperLockKey lockKey;

	private InterProcessReadWriteLock lock;

	private InterProcessMutex readLock;

	@Override
	public void setLockKey(LockKey lockKey) {
		this.lockKey = (ZookeeperLockKey) lockKey;
	}

	@Override
	public void lock() throws Exception {
		lock = new InterProcessReadWriteLock(lockCuratorClient, this.lockKey.getLockPath().get(0));
		readLock = lock.readLock();
		boolean success = readLock.acquire(lockKey.getWaitTime(), lockKey.getTimeUnit());
		if (!success) {
			throw new LockFailException("加锁失败");
		}
	}

	@Override
	public void release() {
		try {
			if (readLock.isAcquiredInThisProcess()) {
				readLock.release();
			}
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

}
